package com.situ.player.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.ListView;

import com.situ.player.R;
import com.situ.player.adapter.FileAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    private ListView mListView;
    private FileAdapter mFileAdapter;
    // 在java里面File既可以表示文件也可以表示文件夹
    // mCurrentDirectoryFile 代表当前正在展示的目录，初始是sd卡根目录
    private File mCurrentDirectory;

    // 存放所有的权限
    private ArrayList<String> mPermissionList = new ArrayList<String>();
    // 需要申请权限
    private ArrayList<String> mAskPermissionList = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Alt+Enter
        mListView = (ListView) findViewById(R.id.list_view);

        // 检查用户权限
        mPermissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        mPermissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        checkPermission(mPermissionList, mAskPermissionList);
        if (mAskPermissionList.size() > 0) {// 有需要申请的权限
            requestPermissions(mAskPermissionList, 1);
        } else {
            // 所有的权限都已经有了
            // 有两种情况：1、是低版本手机 2、高版本手机，但是已经允许了所有的权限
            mFileAdapter = new FileAdapter(this);
            mCurrentDirectory = getSDPath();
            mFileAdapter.updateData(mCurrentDirectory);

            mListView.setAdapter(mFileAdapter);
        }
    }

    /***
     * 请求权限的方法，requestPermissions() 传入一个Activity，一个需要的权限的数组，
     * 和一个整形的request code，与用户完成交互后，系统会回调该方法并返回对用的request code
     * @param needAskPermisson
     * @param requestCode
     */
    private void requestPermissions(ArrayList<String> needAskPermisson, int requestCode) {
        String[] needpermisson = new String[needAskPermisson.size()];
        needpermisson = needAskPermisson.toArray(needpermisson);
        ActivityCompat.requestPermissions(this, needpermisson, 1);//弹出对话框
    }

    /****
     * 判断应用权限的有无，如果没有这项权限，则将权限加入到askPermissionsList
     * @param permissionList
     * @param askpermissionsList
     */
    private void checkPermission(ArrayList<String> permissionList, ArrayList<String> askpermissionsList) {
        for (int i = 0; i < permissionList.size(); i++) {
            //检查权限的方法，第一个参数是context，第二个参数是权限名，返回值为PERMISSION_GRANTED（有权限）和PERMISSION_DENIED(无权限）
            if (ContextCompat.checkSelfPermission(this, permissionList.get(i)) != PackageManager.PERMISSION_GRANTED) {
                askpermissionsList.add(permissionList.get(i));
            }
        }
    }

    // 返回用户在申请权限框选择的结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (verifyPermisson(grantResults)) {// 用户允许了这个权限
            mFileAdapter = new FileAdapter(this);
            mCurrentDirectory = getSDPath();
            mFileAdapter.updateData(mCurrentDirectory);

            mListView.setAdapter(mFileAdapter);
        } else {
            finish();
        }
    }

    // 在确认框里面验证用户到底允不允许这个权限
    private boolean verifyPermisson(int[] grantResults) {
        if (grantResults.length < 1) {
            return false;
        }
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 返回SD卡根目录
     * @return
     */
    private File getSDPath() {
        File sdCard = null;
        boolean isSDExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (isSDExist) {
            // SD卡根目录
            sdCard = Environment.getExternalStorageDirectory();
        } else {
            sdCard = Environment.getRootDirectory();
        }
        return sdCard;
    }

    public void updateCurrentDirectory(File currentDirectory) {
        mCurrentDirectory = currentDirectory;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 值处理back按键
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (mCurrentDirectory.equals(Environment.getExternalStorageDirectory())) {
                finish();
            } else {// 不是SD卡根目录
                String parentPath = mCurrentDirectory.getParent();
                mCurrentDirectory = new File(parentPath);
                mFileAdapter.updateData(mCurrentDirectory);
            }

            return true;
        }

        return super.onKeyDown(keyCode, event);
    }
}
